package com.skynet.app.api.auth.service.impl;

import com.skynet.app.api.auth.repository.UserAuthRepository;
import com.skynet.app.api.auth.entity.User;
import com.skynet.app.api.auth.enums.ResultEnum;
import com.skynet.app.api.auth.exception.UserAuthException;
import com.skynet.app.api.auth.util.JwtUserFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.Collections;

/**
 * @author Skynet
 * @date 2017年11月24日 16:48
 */
@Service
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserAuthRepository userAuthRepository;

    @Override
    public UserDetails loadUserByUsername(String email) {
        User user = userAuthRepository.findByEmail(email);
        if (user == null) {
            log.error("【用户登录】该邮箱未被注册，email={}", email);
            throw new UserAuthException(ResultEnum.USER_NOT_FOUND_BY_EMAIL);
        } else {
            user.setRoles(Collections.singletonList("ADMIN"));
            return JwtUserFactory.create(user);
        }
    }
}